package com.game.ghost.webapp.apps.service.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;

import com.game.ghost.webapp.apps.data.PlayResponse;
import com.game.ghost.webapp.apps.data.WordDictionary;
import com.game.ghost.webapp.apps.player.GamePlayer;
import com.game.ghost.webapp.apps.service.GhostExecutor;
import com.game.ghost.webapp.apps.service.GhostWordsService;

/**
 * 
 * @author gautak
 *
 */
@Service
public class GhostExecutorImpl implements GhostExecutor {

	private static Log logger_ = LogFactory.getLog(GhostExecutorImpl.class);
	
	@Autowired
	private GhostWordsService ghostWordsService;
		
	private MessageSource messageSource = null;
	
    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

	@Autowired
	@Qualifier(value = "systemPlayer")
	private GamePlayer systemPlayer;
	
	public PlayResponse execute(String wordInPlay, String enteredLetter, PlayResponse playResponse){
		
		MessageSourceAccessor text = new MessageSourceAccessor(messageSource);
		
		StringBuffer newWordInPlay = new StringBuffer();
		
		newWordInPlay.append(wordInPlay).append(enteredLetter);
		
		WordDictionary wordDictionary = null;
		
		playResponse.setWordInPlay(newWordInPlay.toString());

		//run UI Player
		
		playResponse.setWordInPlay(newWordInPlay.toString());
		
		wordDictionary = ghostWordsService.getWordDictionary(wordInPlay, enteredLetter);
		
		if (wordDictionary.size() == 0) {
			playResponse.setGameOver(true);
			playResponse.setGameStatus(text.getMessage("game.user.lost.no.word.remaining", new Object[] { newWordInPlay }));
			return playResponse;
		} else if ((wordDictionary.size() == 1)
				&& wordDictionary.firstWord().equals(newWordInPlay.toString())) {
			playResponse.setGameOver(true);
			playResponse.setGameStatus(text.getMessage("game.user.won", new Object[] { newWordInPlay }));
			
			return playResponse;
		}
		
		
		//run System Player
		
		Character nextSystemChar = systemPlayer.play(newWordInPlay.toString());
		
		wordDictionary = ghostWordsService.getWordDictionary(newWordInPlay.toString(), nextSystemChar.toString());
		
		String systemGeneratedWord = newWordInPlay.append(nextSystemChar).toString();
		
		playResponse.setWordInPlay(systemGeneratedWord);
		
		if ((wordDictionary.size() == 1)
				&& wordDictionary.firstWord().equals(systemGeneratedWord)) {
			playResponse.setGameOver(true);
			playResponse.setGameStatus(text.getMessage("game.user.lost.computer.win", new Object[] { systemGeneratedWord }));
			
			return playResponse;
		}
		
		return playResponse;
		
	}
	
}
